package org.lyl.taobao.dao.impl;

import org.lyl.taobao.api.entity.ShopCart;
import org.lyl.taobao.api.utils.DruidConnectionUtils;
import org.lyl.taobao.dao.IShopCartDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Re
 * @Date: 2021/4/7 17:32
 */
public class ShopCartDaoImpl implements IShopCartDao {
    DruidConnectionUtils druidConnectionUtils=new DruidConnectionUtils();
    @Override
    public boolean addShopCart(Connection connection, ShopCart shopCart) {
        PreparedStatement preparedStatement = null;
        String sql = "insert into shopingcart(userId,c_Id,merchantId) values (?,?,?);";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,shopCart.getShopCartUserId());
            preparedStatement.setInt(2,shopCart.getShopCartCommodityId());
            preparedStatement.setInt(3,shopCart.getShopCartMerchantId());
            if (preparedStatement.executeUpdate() == 1) {
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            druidConnectionUtils.closeConnection(connection,preparedStatement,null);
        }
        return false;
    }

    @Override
    public List<Integer> checkC_IdByUserId(Connection connection, Integer userId) {
        List<Integer> integerList = new ArrayList<>();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String sql = "select * from shopingcart where userId = ?";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,userId);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                integerList.add(resultSet.getInt("c_Id"));
            }
            return integerList;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            druidConnectionUtils.closeConnection(connection,preparedStatement,resultSet);
        }
        return null;
    }

    @Override
    public boolean deleteShopCart(Connection connection, Integer userId, Integer c_Id) {
        PreparedStatement preparedStatement = null;
        String sql = "delete from shopingcart where userId = ? and c_Id = ?;";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,userId);
            preparedStatement.setInt(2,c_Id);
            if(preparedStatement.executeUpdate() == 1){
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            druidConnectionUtils.closeConnection(connection,preparedStatement,null);
        }
        return false;
    }
}
